<template>
  <div>
    <el-collapse-transition>
      <card-search v-if="searchCardShow">
        <el-form ref="form" :model="form" label-width="80px" :inline="true">
          <el-form-item label="所有项目">
            <el-select
              v-model="value"
              placeholder="请选择"
              style="width: 250px"
              clearable
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="分组状态">
            <el-select
              v-model="value"
              placeholder="请选择"
              style="width: 250px"
              clearable
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button class="btn-search" round icon="el-icon-search" size="medium"
              >搜索</el-button
            >
            <el-button class="btn-search" round icon="el-icon-refresh" size="medium"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </card-search>
    </el-collapse-transition>

    <card-table style="height: calc(100vh - 100px)">
      <div class="card-table-header">
        <div class="card-table-header-btns">
          <el-button
            v-if="isSuperAdmin || hasPermission('system:group:add')"
            class="btn-search"
            size="small"
            icon="el-icon-plus"
            @click="handleClick(null, 'add')"
            >新增</el-button
          >
          <el-button
            v-if="isSuperAdmin || hasPermission('system:group:remove')"
            class="btn-search"
            size="small"
            icon="el-icon-close"
            @click="handleClick(null, 'deleteSelect')"
            :disabled="btnDisabled"
            >删除</el-button
          >
          <el-button class="btn-search" size="small" @click="toggleExpandAll">
            <svg-icon
              icon-class="collaspe"
              style="margin-right: 5px"
            />展开/折叠</el-button
          >
          <el-input
            v-if="isSuperAdmin || hasPermission('system:group:list')"
            style="width: 250px; margin-left: 10px"
            clearable
            placeholder="请输入分组名称"
            size="small"
            ><el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </div>
        <div class="card-table-header-actions">
          <table-action
            :table-header="tableHeader"
            :search-show="isSuperAdmin || hasPermission('system:group:list')"
            @check-change="handleCheckChange"
            @search-click="handleSearchClick"
            @init-click="handleInitClick"
          />
        </div>
      </div>

      <el-table
        :key="tableKey"
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        :header-cell-style="{ background: '#eff3f8', color: '#333' }"
        border
        stripe
        row-key="id"
        :default-expand-all="false"
        :tree-props="{
          children: 'children',
          hasChildren: 'hasChildren',
          indent: 20,
        }"
        :max-height="tableHeight"
        size="small"
        highlight-selection-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column
          v-for="item in tableHeader"
          v-if="item.visible"
          :key="item.prop"
          :label="item.title"
          :prop="item.prop"
          :align="item.align"
          sortable
          :show-overflow-tooltip="true"
        >
          <template v-if="item.prop === 'name'" #default="scope">
            <span @click="handleClick(scope.row, 'goList')">
              <svg-icon
                icon-class="group-list"
                style="width: 16px; height: 16px; fill: #165eff"
              ></svg-icon>
              <el-tooltip :content="`查看${scope.row[item.prop]}列表`" placement="top">
                <span style="margin-left: 5px; cursor: pointer">{{
                  scope.row[item.prop]
                }}</span>
              </el-tooltip></span
            >
          </template>
          <template v-else #default="scope">
            <div
              v-if="item.prop === 'chart'"
              class="link-type"
              @click="handleClick(scope.row, 'chart')"
            >
              <svg-icon
                icon-class="chartIcon"
                style="width: 18px; height: 18px; fill: #165eff"
              ></svg-icon>
            </div>
            <div
              v-else-if="item.prop === 'status'"
              class="link-type"
              @click="handleClick(scope.row, 'totleList')"
            >
              <el-tooltip class="item" effect="dark" content="查看设备" placement="right">
                <span> {{ scope.row[item.prop] }}</span>
              </el-tooltip>
            </div>
            <div
              v-else-if="item.prop === 'createTime'"
              class="link-type"
              @click="handleClick(scope.row, 'devOnline')"
            >
              <el-tooltip
                class="item"
                effect="dark"
                content="查看在线设备"
                placement="right"
              >
                <span style="color: #1ab394"> {{ scope.row[item.prop] }}</span>
              </el-tooltip>
            </div>
            <div
              v-else-if="item.prop === 'devOffline'"
              class="link-type"
              @click="handleClick(scope.row, 'devOffline')"
            >
              <el-tooltip
                class="item"
                effect="dark"
                content="查看离线设备"
                placement="right"
              >
                <span style="color: red"> {{ scope.row[item.prop] }}</span>
              </el-tooltip>
            </div>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          width="280"
          align="center"
          v-if="
            isSuperAdmin ||
            hasPermission('system:group:edit') ||
            hasPermission('system:group:add') ||
            hasPermission('system:group:remove')
          "
        >
          <template slot-scope="scope">
            <el-button
              v-if="isSuperAdmin || hasPermission('system:group:edit')"
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleClick(scope.row, 'edit')"
              >编辑</el-button
            >
            <el-button
              v-if="isSuperAdmin || hasPermission('system:group:add')"
              type="primary"
              size="mini"
              icon="el-icon-plus"
              @click="handleClick(scope.row, 'add')"
              >新增</el-button
            >
            <el-button
              v-if="isSuperAdmin || hasPermission('system:group:remove')"
              type="primary"
              size="mini"
              icon="el-icon-delete"
              @click="handleClick(scope.row, 'add')"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <XyPagination
        :total="total"
        :pageSizeNum="pageSize"
        :pageNum="currentPage"
        @pagination="handlerPagination"
      ></XyPagination>
    </card-table>

    <dialog-menu
      v-model="dialogMenuVisible"
      :field="field"
      @close="
        () => {
          dialogMenuVisible = false;
        }
      "
    />
    <el-dialog
      :title="field"
      :visible.sync="dialogVisible"
      width="1400px"
      @click="handleDialogClose"
      custom-class="dialog-search-form"
    >
      <div class="group-dialog">
        <el-card v-if="field == '设备列表'">
          <DeviceList :deviceList="deviceList"> </DeviceList>
        </el-card>
        <div v-if="field == '能耗看板'"><EnergyList></EnergyList></div>
      </div>
    </el-dialog>
    <el-dialog :title="field" :visible.sync="dialogCountVisible" width="1200px">
      <DeviceCount :deviceList="deviceList"></DeviceCount>
    </el-dialog>
  </div>
</template>
<script>
import CardTable from "@/components/CardTable";
import CardSearch from "@/components/CardSearch";
import TableAction from "@/components/TableAction";
import DialogMenu from "./component/DialogMenu.vue";
import DeviceList from "./component/deviceList.vue";
import EnergyList from "./component/energyList.vue";
import DeviceCount from "./component/deviceCountlist.vue";
import XyPagination from "@/components/XyPagination";
import { hasPermission, isSuperAdmin } from "@/utils/hasBtnPermission";
export default {
  data() {
    return {
      tableKey: 0, // 用于强制刷新表格
      searchCardShow: false,
      dialogVisible: false,
      btnDisabled: true,
      input: "",
      form: {},
      showIndex: 0,
      options: [
        {
          value: "0",
          label: "所有",
        },
        {
          value: "1",
          label: "正常",
        },
        {
          value: "2",
          label: "停用",
        },
      ],

      value: "0",
      tableHeader: [
        {
          title: "分组名称",
          prop: "name",
          align: "left",
          visible: true,
        },
        {
          title: "数据图表",
          prop: "chart",
          align: "center",
          visible: true,
        },
        {
          title: "分组描述",
          prop: "des",
          align: "center",

          visible: true,
        },
        {
          title: "设备数量",
          prop: "status",
          align: "center",
          visible: true,
        },
        {
          title: "在线数量",
          prop: "createTime",
          align: "center",
          visible: true,
        },
        {
          title: "离线数量",
          prop: "devOffline",
          align: "center",
          visible: true,
        },
      ],
      tableData: [
        {
          id: 1,
          chart: "1",
          name: "王小虎1",
          status: "5",
          des: "存放未分组设备",
          createTime: "2",
          devOffline: "1",
        },
        {
          id: 2,
          chart: "1",
          name: "王小虎3",
          status: "5",
          createTime: "2",
          devOffline: "1",
          des: "存放未分组设备",
          children: [
            {
              id: 21,
              chart: "1",
              name: "王小虎1",
              status: "5",
              createTime: "2",
              devOffline: "1",
              des: "存放未分组设备",
              children: [
                {
                  id: 221,
                  chart: "1",
                  name: "王小虎1",
                  status: "5",
                  createTime: "2",
                  des: "存放未分组设备",
                  devOffline: "1",
                },
                {
                  id: 222,
                  chart: "1",
                  name: "王小虎1",
                  status: "5",
                  createTime: "2",
                  devOffline: "1",
                },
              ],
            },
            {
              id: 22,
              chart: "1",
              name: "王小虎1",
              des: "存放未分组设备",
              status: "5",
              createTime: "2",
              devOffline: "1",
            },
          ],
        },
        {
          id: 3,
          chart: "1",
          name: "王小虎1",
          status: "5",
          createTime: "2",
          devOffline: "1",
          children: [
            {
              id: 31,
              chart: "1",
              name: "王小虎1",
              status: "5",
              createTime: "2",
              devOffline: "1",
            },
            {
              id: 32,
              chart: "1",
              name: "王小虎1",
              status: "5",
              createTime: "2",
              devOffline: "1",
            },
          ],
        },
      ],
      selectedRow: "", // 添加选中行的跟踪变量
      expandedAll: false, // 控制是否全部展开
      currentPage: 1,
      pageSize: 20,
      total: 0,
      tableHeight: 550,
      dialogMenuVisible: false,
      dialogCountVisible: false,
      multipleSelection: [],
      field: "",
      deviceList: [
        {
          projectName: "KTWG15980001",
          projectAdmin: "智能空调3",
          company: "香缇澜山二期",
          totleNum: "-",
          onlineNum: "-",
          offlineNum: "空调交流lora",
          personInCharge: "离线",
          address: "21.9℃",
          outdoorTemp: "14.0℃",
          switchStatus: "关机",
          targetTemp: "22℃",
          workStatus: "运行中",
          networkLock: "锁定后台",
          tempMode: "-",
          schedule: "已启用",
          signalStrength: "90",
          remark: "-",
        },
        {
          projectName: "KTWG15980001",
          projectAdmin: "智能空调4",
          company: "香缇澜山二期",
          totleNum: "-",
          onlineNum: "-",
          offlineNum: "空调交流lora",
          personInCharge: "在线",
          address: "21.9℃",
          outdoorTemp: "14.0℃",
          switchStatus: "关机",
          targetTemp: "22℃",
          workStatus: "运行中",
          networkLock: "全锁",
          tempMode: "-",
          schedule: "已启用",
          signalStrength: "90",
          remark: "-",
        },
      ],
    };
  },
  components: {
    CardTable,
    CardSearch,
    TableAction,
    DialogMenu,
    DeviceList,
    EnergyList,
    DeviceCount,
    XyPagination,
  },
  computed: {
    isSuperAdmin() {
      return isSuperAdmin();
    },
  },
  mounted() {
    this.calculateTableHeight();
    this.initTable();
  },
  methods: {
    initTable() {},
    handlerPagination(page) {
      this.currentPage = page.pageNum;
      this.pageSize = page.pageSize;
      this.initTable();
    },
    handleClick(row, filed) {
      switch (filed) {
        case "edit":
          this.dialogMenuVisible = true;
          this.field = "修改分组";
          break;
        case "add":
          this.dialogMenuVisible = true;
          this.field = "添加分组";
          break;
        case "goList":
          this.dialogVisible = true;
          this.field = "设备列表";
          break;
        case "chart":
          this.dialogVisible = true;
          this.field = "能耗看板";
          break;
        case "totleList":
          this.dialogCountVisible = true;
          this.field = "设备列表";
          break;
        case "devOnline":
          this.dialogCountVisible = true;
          this.field = "在线设备列表";
          break;
        case "devOffline":
          this.dialogCountVisible = true;
          this.field = "离线设备列表";
          break;
        case "deleteSelect":
          this.$confirm(
            `确认删除选中的${this.multipleSelection.length}个分组吗?`,
            "系统提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          ).then(() => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          });
          break;
        default:
          break;
      }
    },

    handleDialogClose() {
      this.dialogVisible = false;
      this.deviceList = [];
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      if (this.multipleSelection.length > 0) {
        this.btnDisabled = false;
      } else {
        this.btnDisabled = true;
      }
    },
    // 处理表头显示隐藏
    handleCheckChange(checkedValues) {
      this.tableHeader.forEach((item) => {
        item.visible = checkedValues.includes(item.prop);
      });
      this.tableKey += 1;
    },
    handleSearchClick() {
      this.searchCardShow = !this.searchCardShow;
      console.log("搜索按钮点击");
    },
    handleInitClick() {
      this.initTable();
    },
    // 展开/折叠所有节点
    toggleExpandAll() {
      this.expandedAll = !this.expandedAll;
      this.tableData.forEach((item) => {
        this.toggleExpanded(item, this.expandedAll);
      });
    },

    // 递归设置节点展开状态
    toggleExpanded(row, expanded) {
      // 设置当前行的展开状态
      this.$refs.multipleTable.toggleRowExpansion(row, expanded);

      // 递归处理子节点
      if (row.children && row.children.length > 0) {
        row.children.forEach((child) => {
          this.toggleExpanded(child, expanded);
        });
      }
    },
    hasPermission(permission) {
      return hasPermission(permission);
    },
    calculateTableHeight() {
      // 根据容器实际高度计算表格高度
      this.$nextTick(() => {
        const container = this.$refs.multipleTable.$el?.parentElement;
        if (container) {
          // 减去表头和其他元素的高度
          this.tableHeight = container.clientHeight - 120; // 120为估计的其他元素高度
        }
      });
    },
  },
};
</script>
<style lang="scss">
.group-dialog,
.device-list,
.energy-list {
  .el-tabs--card > .el-tabs__header .el-tabs__nav .el-tabs__item {
    width: 150px;
    text-align: center;
    background-color: #dfe6ec;
    color: #3d3d3d;
    border-top-left-radius: 10px;
    // border-top-right-radius: 15px;
    margin-left: -10px;
    border: 1px solid #fff;
  }
  .el-tabs--card > .el-tabs__header .el-tabs__nav .el-tabs__item:first-child {
    margin-left: 0;
  }
  .el-tabs--card > .el-tabs__header .el-tabs__nav .el-tabs__item.is-active {
    background-color: #165eff;
    color: #fff;
  }
  .el-tabs--card > .el-tabs__header .el-tabs__nav {
    border: 1px solid #fff;
  }
  .el-tabs__nav-wrap {
    margin-top: -2px;
  }
  .el-tabs--card > .el-tabs__header {
    border-bottom: 1px solid #dfe6ec;
    margin: 0;
  }
}
</style>
